﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Interop;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Unity;

namespace CustomControls.ColorPicker
{
    /// <summary>
    /// 取色器
    /// </summary>
    public partial class ColorControlPanel : UserControl
    {
        ControlColors ColorPanelColors = new ControlColors();
        public ColorControlPanel()
        {
            InitializeComponent();
            this.DataContext = ColorPanelColors;
            this.Loaded += delegate
            {
                DrawColorWheel();
            };
            RegisterEvent();
        }

        #region 属性字段
        // 定义初始颜色(依赖属性)
        public static readonly DependencyProperty InitialBrushProperty =
            DependencyProperty.Register("InitialBrush", typeof(SolidColorBrush), typeof(ColorControlPanel),
                new FrameworkPropertyMetadata(new SolidColorBrush(Colors.Red),
                    new PropertyChangedCallback(InitialBrushChanged)));
        public SolidColorBrush InitialBrush
        {
            get { return (SolidColorBrush)GetValue(InitialBrushProperty); }
            set { SetValue(InitialBrushProperty, value); }
        }
        private static void InitialBrushChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
        {
            ColorControlPanel panel = (ColorControlPanel)sender;
            panel.ColorPanelColors.InitialBrush = e.NewValue as SolidColorBrush;
        }
        // 定义选定颜色(依赖属性)
        public static readonly DependencyProperty SelectBrushProperty =
            DependencyProperty.Register("SelectBrush", typeof(SolidColorBrush), typeof(ColorControlPanel),
                new FrameworkPropertyMetadata(new SolidColorBrush(Colors.Lime),
                    new PropertyChangedCallback(SelectBrushChanged)));
        public Brush SelectBrush
        {
            get { return (Brush)GetValue(SelectBrushProperty); }
            set { SetValue(SelectBrushProperty, value); }
        }
        private static void SelectBrushChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
        {
            ColorControlPanel panel = (ColorControlPanel)sender;
            panel.SelectBrush = e.NewValue as SolidColorBrush;
            panel.ColorPanelColors.SelectedBrush = e.NewValue as SolidColorBrush;
        }
        // 定义字体颜色(依赖属性)
        public static readonly DependencyProperty TextForeColorProperty =
            DependencyProperty.Register("TextForeColor", typeof(SolidColorBrush), typeof(ColorControlPanel),
                new FrameworkPropertyMetadata(new SolidColorBrush(Colors.Lime),
                    new PropertyChangedCallback(SelectBrushChanged)));
        public SolidColorBrush TextForeColor
        {
            get { return (SolidColorBrush)GetValue(SelectBrushProperty); }
            set { SetValue(SelectBrushProperty, value); }
        }
        private static void TextForeColorChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
        {
            ColorControlPanel panel = (ColorControlPanel)sender;
            panel.SelectBrush = e.NewValue as SolidColorBrush;
        }
        #endregion

        // 注册控件事件
        private void RegisterEvent()
        {
            // 色相变更事件
            PanelHue.MouseLeftButtonDown += delegate
            {
                HueThumbMove(Mouse.GetPosition(PanelHue));
            };
            PanelHue.MouseMove += delegate (object sender, MouseEventArgs e)
            {
                if (e.LeftButton == MouseButtonState.Pressed)
                {
                    if (Mouse.Captured == null) Mouse.Capture(PanelHue);
                    HueThumbMove(e.GetPosition(PanelHue));
                }
                else Mouse.Capture(null);
            };
            // 饱和度&色调变更事件
            PanelSV.MouseLeftButtonDown += delegate
            {
                SvThumbMove(Mouse.GetPosition(this));
            };
            PanelSV.MouseMove += delegate (object sender, MouseEventArgs e)
            {
                if (e.LeftButton == MouseButtonState.Pressed)
                {
                    if (Mouse.Captured == null) Mouse.Capture(PanelSV);
                    SvThumbMove(e.GetPosition(this));
                }
                else Mouse.Capture(null);
            };
            // 颜色代码更改事件
            ColorCodeValue.KeyUp += delegate (object sender, KeyEventArgs e)
            {
                if (e.Key == Key.Enter)
                {
                    NewBrush.Focus();
                }
                if (e.Key == Key.Escape)
                {
                    ColorCodeValue.Text = NewBrush.Background.ToString(); ;
                    ColorCodeValue.SelectAll();
                }
            };
            // 选定颜色变更事件
            ColorCodeValue.TextChanged += delegate
            {
                SelectColorChanged();
            };
            // 还原默认颜色
            OldBrush.MouseLeftButtonDown += delegate
            {
                ColorPanelColors.SelectedBrush = (SolidColorBrush)OldBrush.Background;
            };
            // 捕捉屏幕颜色
            NewBrush.MouseMove += delegate (object sender, MouseEventArgs e)
            {
                if (e.LeftButton == MouseButtonState.Pressed)
                {
                    if (Mouse.Captured == null)
                    {
                        Mouse.Capture(NewBrush);
                        ShowCapture.Source = ColorPicker.ScreenSnapshot();
                        Magnifier.Visibility = Visibility.Visible;
                    }
                    Point mousePoint = PointToScreen(e.GetPosition(this));
                    ShowPoint.Text = String.Format("{0},{1}", mousePoint.X + 1, mousePoint.Y + 1);
                    ShowCapture.SetValue(Canvas.LeftProperty, -20 * mousePoint.X);
                    ShowCapture.SetValue(Canvas.TopProperty, -20 * mousePoint.Y);
                    ColorPanelColors.SelectedColor = ColorPicker.PointColor(mousePoint);
                }
                else
                {
                    Mouse.Capture(null);
                    Magnifier.Visibility = Visibility.Collapsed;
                }
            };
            // 允许鼠标滚轮控制滑条
            SliderR.MouseWheel += MouseWhellSlider;
            SliderG.MouseWheel += MouseWhellSlider;
            SliderB.MouseWheel += MouseWhellSlider;
            SliderH.MouseWheel += MouseWhellSlider;
            SliderS.MouseWheel += MouseWhellSlider;
            SliderV.MouseWheel += MouseWhellSlider;
        }

        /// <summary>
        /// 鼠标滚轮控制滑条
        /// </summary>
        /// <param name="sender">焦点滑条</param>
        /// <param name="e">滚轮数据</param>
        private void MouseWhellSlider(object sender, MouseWheelEventArgs e)
        {
            Slider FocusSlider = sender as Slider;
            if (e.Delta > 0)
            {
                if (FocusSlider.Value + FocusSlider.TickFrequency > FocusSlider.Maximum)
                {
                    FocusSlider.Value = FocusSlider.Maximum;
                }
                else
                {
                    FocusSlider.Value += FocusSlider.TickFrequency;
                }
            }
            if (e.Delta < 0)
            {
                if (FocusSlider.Value - FocusSlider.TickFrequency < FocusSlider.Minimum)
                {
                    FocusSlider.Value = FocusSlider.Minimum;
                }
                else
                {
                    FocusSlider.Value -= FocusSlider.TickFrequency;
                }
            }

        }

        /// <summary>
        /// 色相改变事件
        /// </summary>
        private void HueThumbMove(Point point)
        {
            double angle = Math.Atan2(point.Y - (PanelHue.ActualHeight / 2), point.X - (PanelHue.ActualWidth / 2)) * 180 / Math.PI;
            if (angle < 0) angle += 360;
            ColorPanelColors.SelectedHue = angle;
        }

        /// <summary>
        /// 饱和度&色调改变事件
        /// </summary>
        /// <param name="point"></param>
        private void SvThumbMove(Point point)
        {
            Point pointSV = this.TranslatePoint(point, PanelSV);
            Point pointS = this.TranslatePoint(point, PanelS);
            Point pointV = this.TranslatePoint(point, PanelV);
            Point pointLUp = PanelSV.Points[2];
            Point pointLDn = PanelSV.Points[1];
            Point pointRMd = PanelSV.Points[0];

            if (pointSV.X < pointLUp.X)
            {
                pointSV.X = pointLUp.X;
                if (pointSV.Y < pointLUp.Y) pointSV.Y = pointLUp.Y;
                if (pointSV.Y > pointLDn.Y) pointSV.Y = pointLDn.Y;
            }
            else if (pointS.X < pointLUp.X)
            {
                pointS.X = pointLUp.X;
                if (pointS.Y < pointLUp.Y) pointS.Y = pointLUp.Y;
                if (pointS.Y > pointLDn.Y) pointS.Y = pointLDn.Y;
                pointSV = PanelS.TranslatePoint(pointS, PanelSV);
            }
            else if (pointV.X < pointLUp.X)
            {
                pointV.X = pointLUp.X;
                if (pointV.Y < pointLUp.Y) pointV.Y = pointLUp.Y;
                if (pointV.Y > pointLDn.Y) pointV.Y = pointLDn.Y;
                pointSV = PanelV.TranslatePoint(pointV, PanelSV);
            }
            ThumbSV.SetValue(Canvas.LeftProperty, pointSV.X);
            ThumbSV.SetValue(Canvas.TopProperty, pointSV.Y);

            ColorHSV selectHSV = ColorPanelColors.SelectedHSV;
            pointV = PanelSV.TranslatePoint(pointSV, PanelV);
            double maxV = pointRMd.X - pointLUp.X;
            double nowV = pointRMd.X - pointV.X;
            selectHSV.V = nowV / maxV;
            double maxS = pointLDn.Y - pointLUp.Y;
            double zomS = maxS * selectHSV.V;
            double nowS = pointLUp.Y + (maxS + zomS) / 2 - pointV.Y;
            selectHSV.S = Math.Round(nowS / zomS, 6);
            selectHSV.V = Math.Round(selectHSV.V, 6);
            ColorPanelColors.SelectedHSV = selectHSV;
        }

        /// <summary>
        /// 选定颜色变更事件处理
        /// </summary>
        private void SelectColorChanged()
        {
            ColorHSV selectHSV = ColorPanelColors.SelectedHSV;
            Point pointLUp = PanelSV.Points[2];
            Point pointLDn = PanelSV.Points[1];
            Point pointRMd = PanelSV.Points[0];
            Point pointV = new Point();
            double maxV = pointRMd.X - pointLUp.X;
            pointV.X = pointRMd.X - maxV * selectHSV.V;
            double maxS = pointLDn.Y - pointLUp.Y;
            double zomS = maxS * selectHSV.V;
            pointV.Y = pointLUp.Y + (maxS + zomS) / 2 - zomS * selectHSV.S;
            Point pointSV = PanelV.TranslatePoint(pointV, PanelSV);
            ThumbSV.SetValue(Canvas.LeftProperty, pointSV.X);
            ThumbSV.SetValue(Canvas.TopProperty, pointSV.Y);
        }

        /// <summary>
        /// 弧线法绘制色环
        /// </summary>
        private void DrawColorWheel()
        {
            // 定义绘图容器
            Canvas colorWheel = xColorWheel;
            // 生成颜色表
            List<Color> wheelColors = new List<Color>();
            for (byte i = 0; i < 255; i++) wheelColors.Add(Color.FromRgb(255, i, 0));
            for (byte i = 255; i > 0; i--) wheelColors.Add(Color.FromRgb(i, 255, 0));
            for (byte i = 0; i < 255; i++) wheelColors.Add(Color.FromRgb(0, 255, i));
            for (byte i = 255; i > 0; i--) wheelColors.Add(Color.FromRgb(0, i, 255));
            for (byte i = 0; i < 255; i++) wheelColors.Add(Color.FromRgb(i, 0, 255));
            for (byte i = 255; i > 0; i--) wheelColors.Add(Color.FromRgb(255, 0, i));
            // 创建绘图变量
            Double centerX = colorWheel.ActualWidth / 2;
            Double centerY = colorWheel.ActualHeight / 2;
            Double radius = (centerX < centerY ? centerX : centerY) * 0.8;
            Double width = (centerX < centerY ? centerX : centerY) * 0.4;
            Double angel = 2.0 * Math.PI / wheelColors.Count;   // 计算夹角
            Double rotate = 0 * Math.PI / 180;                  // 设置圆周绘图起点角度

            Point pointA = new Point();                         // 缓存绘图路径起点
            Point pointB = new Point();                         // 缓存绘图路径终点
            // 计算绘图路径并填充颜色(后一个颜色覆盖前一个颜色50%角度)
            wheelColors.ForEach((color) =>
            {
                pointA.X = centerX + radius * Math.Cos(rotate);
                pointA.Y = centerY + radius * Math.Sin(rotate);
                rotate += angel;
                pointB.X = centerX + radius * Math.Cos(rotate + angel);
                pointB.Y = centerY + radius * Math.Sin(rotate + angel);
                PathFigure wheelPath = new PathFigure() { StartPoint = pointA };
                wheelPath.Segments.Add(new ArcSegment() { Point = pointB, Size = new Size(radius, radius) });
                PathGeometry wheelPaths = new PathGeometry(new PathFigureCollection() { wheelPath });
                colorWheel.Children.Add(new Path() { StrokeThickness = width, Stroke = new SolidColorBrush(color), Data = wheelPaths });
            });
            // 补足被覆盖的起始角度颜色块
            if (rotate > 360)
            {
                pointA.X = centerX + radius * Math.Cos(0);
                pointA.Y = centerY + radius * Math.Sin(0);
                pointB.X = centerX + radius * Math.Cos(angel);
                pointB.Y = centerY + radius * Math.Sin(angel);
                PathFigure wheelPath = new PathFigure() { StartPoint = pointA };
                wheelPath.Segments.Add(new ArcSegment() { Point = pointB, Size = new Size(radius, radius) });
                PathGeometry wheelPaths = new PathGeometry(new PathFigureCollection() { wheelPath });
                colorWheel.Children.Add(new Path() { StrokeThickness = width, Stroke = new SolidColorBrush(wheelColors[0]), Data = wheelPaths });
            }
        }
    }

    /// <summary>
    /// 使用 色相、饱和度、色调 表示的颜色,初始化值为H=0、S=1、V=1
    /// </summary>
    public partial class ColorHSV
    {
        public double H = 0;
        public double S = 1;
        public double V = 1;
    }

    // 实现前端数据绑定接口
    public class ControlColors : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;
        private void Notify(string notifyName)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(notifyName));
        }
        private void OnInitialChanged()
        {
            Notify("InitialColor");
            Notify("InitialBrush");
        }
        private void OnSelectedChanged(string mode = "RGB")
        {
            if (mode == "RGB")
            {
                hsvColor = ConvertRgbToHsv(newColor);
            }
            else
            {
                if (hsvColor.S > 1) hsvColor.S = 0.5;
                newColor = ConvertHsvToRgb(hsvColor);
            }
            List<string> NotifyNames = new List<string>()
            {
            "SelectedColor",
            "SelectedBrush",
            "SelectedBrushValue",
            "SelectedColorR",
            "SelectedColorG",
            "SelectedColorB",
            "SelectedGradientR",
            "SelectedGradientG",
            "SelectedGradientB",
            "SelectedBrushR",
            "SelectedBrushG",
            "SelectedBrushB",
            "SelectedHSV",
            "SelectedHue",
            "SelectedSat",
            "SelectedVal",
            "SelectedBrushH",
            "SelectedValH",
            "SelectedValS",
            "SelectedValV"
            };
            NotifyNames.ForEach((name) => { Notify(name); });
        }

        private Color oldColor = Colors.Lime;
        public Color InitialColor
        {
            get { return oldColor; }
            set { oldColor = value; OnInitialChanged(); }
        }
        public Brush InitialBrush
        {
            get { return new SolidColorBrush(oldColor); }
            set { oldColor = (Color)ColorConverter.ConvertFromString(value.ToString()); OnInitialChanged(); }
        }

        private Color newColor = Colors.Red;
        public Color SelectedColor
        {
            get { return newColor; }
            set { newColor = value; OnSelectedChanged(); }
        }
        public Brush SelectedBrush
        {
            get { return new SolidColorBrush(newColor); }
            set { newColor = (Color)ColorConverter.ConvertFromString(value.ToString()); OnSelectedChanged(); }
        }

        public String SelectedBrushValue
        {
            get { return newColor.ToString(); }
            set
            {
                try
                {
                    newColor = (Color)ColorConverter.ConvertFromString(value);
                }
                catch (Exception ex)
                {
                    LogHelper.Error(string.Format("(类)ColorControlPanel-->(方法)SelectedBrushValue:{0}\r\n{1}", ex.Message,ex.StackTrace));
                }
                OnSelectedChanged();
            }
        }
        public LinearGradientBrush SelectedGradientR
        {
            get
            {
                LinearGradientBrush gradientBrush = new LinearGradientBrush()
                {
                    StartPoint = new Point(0, 0.5),
                    EndPoint = new Point(1, 0.5)
                };
                GradientStop colorStart = new GradientStop(Color.FromRgb(0, newColor.G, newColor.B), 0);
                GradientStop colorEnd = new GradientStop(Color.FromRgb(255, newColor.G, newColor.B), 1);
                gradientBrush.GradientStops.Add(colorStart);
                gradientBrush.GradientStops.Add(colorEnd);
                return gradientBrush;
            }
        }
        public LinearGradientBrush SelectedGradientG
        {
            get
            {
                LinearGradientBrush gradientBrush = new LinearGradientBrush()
                {
                    StartPoint = new Point(0, 0.5),
                    EndPoint = new Point(1, 0.5)
                };
                GradientStop colorStart = new GradientStop(Color.FromRgb(newColor.R, 0, newColor.B), 0);
                GradientStop colorEnd = new GradientStop(Color.FromRgb(newColor.R, 255, newColor.B), 1);
                gradientBrush.GradientStops.Add(colorStart);
                gradientBrush.GradientStops.Add(colorEnd);
                return gradientBrush;
            }
        }
        public LinearGradientBrush SelectedGradientB
        {
            get
            {
                LinearGradientBrush gradientBrush = new LinearGradientBrush()
                {
                    StartPoint = new Point(0, 0.5),
                    EndPoint = new Point(1, 0.5)
                };
                GradientStop colorStart = new GradientStop(Color.FromRgb(newColor.R, newColor.G, 0), 0);
                GradientStop colorEnd = new GradientStop(Color.FromRgb(newColor.R, newColor.G, 255), 1);
                gradientBrush.GradientStops.Add(colorStart);
                gradientBrush.GradientStops.Add(colorEnd);
                return gradientBrush;
            }
        }
        public SolidColorBrush SelectedBrushR
        {
            get { return new SolidColorBrush(Color.FromRgb(newColor.R, 0, 0)); }
        }
        public SolidColorBrush SelectedBrushG
        {
            get { return new SolidColorBrush(Color.FromRgb(0, newColor.G, 0)); }
        }
        public SolidColorBrush SelectedBrushB
        {
            get { return new SolidColorBrush(Color.FromRgb(0, 0, newColor.B)); }
        }
        public byte SelectedColorR
        {
            get { return newColor.R; }
            set
            {
                newColor.R = value;
                OnSelectedChanged();
            }
        }
        public byte SelectedColorG
        {
            get { return newColor.G; }
            set
            {
                newColor.G = value;
                OnSelectedChanged();
            }
        }
        public byte SelectedColorB
        {
            get { return newColor.B; }
            set
            {
                newColor.B = value;
                OnSelectedChanged();
            }
        }

        private ColorHSV hsvColor = new ColorHSV() { H = 0, S = 1, V = 1 };
        public ColorHSV SelectedHSV
        {
            get { return hsvColor; }
            set { hsvColor = value; OnSelectedChanged("HSV"); }
        }
        public Double SelectedHue
        {
            get { return hsvColor.H; }
            set { hsvColor.H = value; OnSelectedChanged("HSV"); }
        }
        public Double SelectedSat
        {
            get { return hsvColor.S * 100; }
            set { hsvColor.S = value / 100; OnSelectedChanged("HSV"); }
        }
        public Double SelectedVal
        {
            get { return hsvColor.V * 100; }
            set { hsvColor.V = value / 100; OnSelectedChanged("HSV"); }
        }
        public SolidColorBrush SelectedBrushH
        {
            get { return new SolidColorBrush(ConvertHsvToRgb(new ColorHSV() { H = hsvColor.H })); }
        }
        public String SelectedValH
        {
            get
            {
                if (hsvColor.H < 100) return Math.Round(hsvColor.H, 1).ToString();
                return Math.Round(hsvColor.H).ToString();
            }
        }
        public String SelectedValS
        {
            get
            {
                if (hsvColor.S < 0.01) return Math.Round(hsvColor.S * 100, 2).ToString();
                else return Math.Round(hsvColor.S * 100, 1).ToString();
            }
        }
        public String SelectedValV
        {
            get
            {
                if (hsvColor.V < 0.01) return Math.Round(hsvColor.V * 100, 2).ToString();
                else return Math.Round(hsvColor.V * 100, 1).ToString();
            }
        }

        /// <summary>
        /// RGB颜色转HSV颜色
        /// </summary>
        /// <param name="color">RGB颜色</param>
        /// <returns>HSV颜色</returns>
        public static ColorHSV ConvertRgbToHsv(Color color)
        {
            ColorHSV colorhsv = new ColorHSV();
            double r = color.R / 255.0;
            double g = color.G / 255.0;
            double b = color.B / 255.0;
            double chroma, min = r, max = r;
            if (g > max) max = g;
            else if (g < min) min = g;
            if (b > max) max = b;
            else if (b < min) min = b;
            colorhsv.V = max;
            chroma = max - min;
            if (colorhsv.V == 0) colorhsv.S = 0;
            else colorhsv.S = chroma / max;
            if (colorhsv.S == 0) colorhsv.H = 0;
            else if (max == r) colorhsv.H = (g - b) / chroma;
            else if (max == g) colorhsv.H = 2 + (b - r) / chroma;
            else colorhsv.H = 4 + (r - g) / chroma;
            colorhsv.H *= 60;
            if (colorhsv.H < 0) colorhsv.H += 360;
            return colorhsv;
        }
        /// <summary>
        /// HSV颜色转RGB颜色
        /// </summary>
        /// <param name="colorhsv">HSV颜色</param>
        /// <returns>RGB颜色</returns>
        public static Color ConvertHsvToRgb(ColorHSV colorhsv)
        {
            if (colorhsv.H > 360) colorhsv.H = 0;
            double chroma = colorhsv.V * colorhsv.S;
            double hueTag = colorhsv.H / 60;
            double x = chroma * (1 - Math.Abs(hueTag % 2 - 1));
            double m = colorhsv.V - chroma;
            double R, G, B;
            switch ((int)hueTag)
            {
                case 0:
                    R = chroma; G = x; B = 0;
                    break;
                case 1:
                    R = x; G = chroma; B = 0;
                    break;
                case 2:
                    R = 0; G = chroma; B = x;
                    break;
                case 3:
                    R = 0; G = x; B = chroma;
                    break;
                case 4:
                    R = x; G = 0; B = chroma;
                    break;
                default:
                    R = chroma; G = 0; B = x;
                    break;
            }
            R += m; G += m; B += m;
            R *= 255; G *= 255; B *= 255;
            return Color.FromRgb((byte)R, (byte)G, (byte)B);
        }
    }

    //  单值转换器(画刷转字符串值)
    //public partial class BrushValueConver : IValueConverter
    //{
    //    //当值从绑定源传播给绑定目标时，调用方法Convert
    //    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    //    {
    //        if (value == null) return DependencyProperty.UnsetValue;
    //        return ((Brush)value).ToString();
    //    }
    //    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    //    {
    //        throw new NotImplementedException();
    //    }
    //}

    /// <summary>
    /// 多值转换器(根据矩形长宽生成内接正三角形坐标点集合)
    /// </summary>
    public partial class EqTriangleConver : IMultiValueConverter
    {
        public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if (values == null || values.Length < 1) return null;

            Double centerX = (double)values[0] / 2;
            Double centerY = (double)values[1] / 2;
            Double radius = (centerX < centerY ? centerX : centerY) * 0.8;
            Int32 sides = 3;
            Double angel = 360 / sides * Math.PI / 180;     // 计算正多边形的临边夹角
            Double rotate = 0 * Math.PI / 180;              // 设置圆周绘图起点角度
            // 计算绘图路径
            PointCollection points = new PointCollection();
            while (--sides >= 0)
            {
                Double pointX = centerX + radius * Math.Cos(rotate);
                Double pointY = centerY + radius * Math.Sin(rotate);
                points.Add(new Point(pointX, pointY));
                rotate += angel;
            }
            return points;
        }

        public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }

    /// <summary>
    /// 获取屏幕坐标颜色(需引用程序集：System.Drawing)
    /// </summary>
    public partial class ColorPicker
    {
        /// <summary>
        /// 获取指定屏幕坐标的颜色值
        /// </summary>
        /// <param name="x">鼠标相对于显示器的坐标X</param>
        /// <param name="y">鼠标相对于显示器的坐标Y</param>
        /// <returns></returns>
        public static Color PointColor(Point point)
        {
            IntPtr hdc = GetDC(IntPtr.Zero);
            uint pixel = GetPixel(hdc, (int)point.X, (int)point.Y);
            ReleaseDC(IntPtr.Zero, hdc);
            Color color = Color.FromRgb((byte)(0xFF & pixel), (byte)(0xFF & (pixel >> 8)), (byte)(0xFF & (pixel >> 16)));
            return color;
        }

        /// <summary>
        /// 获取屏幕截图
        /// </summary>
        /// <returns></returns>
        public static BitmapSource ScreenSnapshot()
        {
            BitmapSource shotBmp;
            using (System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(
                    (int)SystemParameters.PrimaryScreenWidth,
                    (int)SystemParameters.PrimaryScreenHeight))
            {
                using (var g = System.Drawing.Graphics.FromImage(bmp))
                {
                    g.CopyFromScreen(0, 0, 0, 0, bmp.Size, System.Drawing.CopyPixelOperation.SourceCopy);
                }
                IntPtr hBitmap = bmp.GetHbitmap();
                try
                {
                    shotBmp = Imaging.CreateBitmapSourceFromHBitmap(hBitmap, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());
                }
                finally
                {
                    DeleteObject(hBitmap);
                }
            }
            return shotBmp;
        }

        /// <summary>
        /// 释放资源
        /// </summary>
        /// <param name="hObject"></param>
        /// <returns></returns>
        [DllImport("gdi32.dll")]
        public static extern bool DeleteObject(IntPtr hObject);

        /// <summary>
        /// 获取指定窗口的设备场景
        /// </summary>
        /// <param name="hwnd">将获取其设备场景的窗口的句柄。若为0，则要获取整个屏幕的DC</param>
        /// <returns>指定窗口的设备场景句柄，出错则为0</returns>
        [DllImport("user32.dll")]
        private static extern IntPtr GetDC(IntPtr hwnd);

        /// <summary>
        /// 释放由调用GetDC函数获取的指定设备场景
        /// </summary>
        /// <param name="hwnd">要释放的设备场景相关的窗口句柄</param>
        /// <param name="hdc">要释放的设备场景句柄</param>
        /// <returns>执行成功为1，否则为0</returns>
        [DllImport("user32.dll")]
        private static extern Int32 ReleaseDC(IntPtr hwnd, IntPtr hdc);

        /// <summary>
        /// 在指定的设备场景中取得一个像素的RGB值
        /// </summary>
        /// <param name="hdc">一个设备场景的句柄</param>
        /// <param name="nXPos">逻辑坐标中要检查的横坐标</param>
        /// <param name="nYPos">逻辑坐标中要检查的纵坐标</param>
        /// <returns>指定点的颜色</returns>
        [DllImport("gdi32.dll")]
        private static extern uint GetPixel(IntPtr hdc, int nXPos, int nYPos);
    }
}